package com.ruoyi.scheduling.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.classrecords.domain.ClassRecords;
import com.ruoyi.classrecords.service.IClassRecordsService;
import com.ruoyi.course.service.ICourseService;
import com.ruoyi.order.domain.Order;
import com.ruoyi.order.service.IOrderService;
import com.ruoyi.orderdeduct.domain.OrderDeduct;
import com.ruoyi.orderdeduct.service.IOrderDeductService;
import com.ruoyi.scheduling.domain.ScheduCount;
import com.ruoyi.schoolclass.domain.Schoolclass;
import com.ruoyi.schoolclass.service.ISchoolclassService;
import com.ruoyi.student.domain.DzStudent;
import com.ruoyi.student.service.IDzStudentService;
import com.ruoyi.utils.Times;
import com.ruoyi.withholdingfees.domain.WithholdingFees;
import com.ruoyi.withholdingfees.service.IWithholdingFeesService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.scheduling.domain.DzCourseScheduling;
import com.ruoyi.scheduling.service.IDzCourseSchedulingService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 课程表Controller
 *
 * @author ruoyi
 * @date 2024-01-11
 */
@RestController
@RequestMapping("/scheduling/scheduling")
public class DzCourseSchedulingController extends BaseController {
    @Autowired
    public IDzCourseSchedulingService dzCourseSchedulingService;
    @Autowired
    private IClassRecordsService classRecordsService;
    @Autowired
    private ICourseService courseService;
    @Autowired
    private ISchoolclassService schoolclassService;

    /**
     * 查询课程表列表
     */
    @PreAuthorize("@ss.hasPermi('scheduling:scheduling:list')")
    @GetMapping("/list")
    public TableDataInfo list(DzCourseScheduling dzCourseScheduling) {

        //不是根据星期几模糊查询，开启分页
        if (dzCourseScheduling.getData2() == null) {
            startPage();
        }

        List<DzCourseScheduling> ccList = new ArrayList<DzCourseScheduling>();
        //根据星期几模糊查询
        List<DzCourseScheduling> list = dzCourseSchedulingService.selectDzCourseSchedulingList(dzCourseScheduling);

        if (dzCourseScheduling.getData2() != null) {
            for (int i = 0; i < list.size(); i++) {
                String week = list.get(i).getData1();
                if (week != null) {
                    if (dzCourseScheduling.getData2().contains(week)) {
                        ccList.add(list.get(i));
                    }
                }


            }
            return getDataTable(ccList);
        } else {
            return getDataTable(list);
        }


    }

    @PreAuthorize("@ss.hasPermi('scheduling:scheduling:list')")
    @GetMapping("/schedulingtablelist")
    public TableDataInfo schedulingtablelist(DzCourseScheduling scheduCount) {
        List<ScheduCount> allScheduCount = Times.getDays(scheduCount.getYear(), scheduCount.getMonth());
        List<ScheduCount> schedulingCount = dzCourseSchedulingService.getSchedulingCount(
                scheduCount.getYear(),
                scheduCount.getMonth(),
                scheduCount.getDeptId(),
                scheduCount.getClassCourse(),
                scheduCount.getClassName(),
                scheduCount.getClassTeacher(),
                scheduCount.getClassStudent()
        );
        List<ScheduCount> getSchedulingCountUnsettled = dzCourseSchedulingService.getSchedulingCountUnsettled(
                scheduCount.getYear(),
                scheduCount.getMonth(),
                scheduCount.getDeptId(),
                scheduCount.getClassCourse(),
                scheduCount.getClassName(),
                scheduCount.getClassTeacher(),
                scheduCount.getClassStudent()
        );


        for (int i = 0; i < allScheduCount.size(); i++) {
            ScheduCount newscheduCount = allScheduCount.get(i);
            for (int w = 0; w < schedulingCount.size(); w++) {
                if (newscheduCount.getDate().equals(schedulingCount.get(w).getDate())) {
                    newscheduCount.setContent(schedulingCount.get(w).getContent());
                    for (int y=0; y<getSchedulingCountUnsettled.size(); y++) {
                        if ( newscheduCount.getDate().equals(getSchedulingCountUnsettled.get(y).getDate())) {
                            if (getSchedulingCountUnsettled.get(y).getContent()>0) {
                                newscheduCount.setHaveNoSettlement(true);
                            } else {
                                newscheduCount.setHaveNoSettlement(false);
                            }


                        }

                    }

                }

            }


        }
        return getDataTable(allScheduCount);

    }

    /**
     * 导出课程表列表
     */
    @PreAuthorize("@ss.hasPermi('scheduling:scheduling:export')")
    @Log(title = "课程表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DzCourseScheduling dzCourseScheduling) {
        List<DzCourseScheduling> list = dzCourseSchedulingService.selectDzCourseSchedulingList(dzCourseScheduling);
        ExcelUtil<DzCourseScheduling> util = new ExcelUtil<DzCourseScheduling>(DzCourseScheduling.class);
        util.exportExcel(response, list, "课程表数据");
    }

    /**
     * 获取课程表详细信息
     */
    @PreAuthorize("@ss.hasPermi('scheduling:scheduling:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(dzCourseSchedulingService.selectDzCourseSchedulingById(id));
    }

    @Autowired
    private IDzStudentService dzStudentService;

    /**
     * 新增课程表
     */
    @PreAuthorize("@ss.hasPermi('scheduling:scheduling:add')")
    @Log(title = "课程表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DzCourseScheduling dzCourseScheduling) {
        try {
            String[] arr = dzCourseScheduling.getData2().split(",");
            System.out.println(arr.length);
            for (int i = 0; i < arr.length; i++) {
                System.out.println(arr[i] + " " + dzCourseScheduling.getClassStart());
                System.out.println(arr[i] + " " + dzCourseScheduling.getClassFinish());


                String type = Times.StateType(arr[i] + " " + dzCourseScheduling.getClassStart(), arr[i] + " " + dzCourseScheduling.getClassFinish());

                //设置上课日期
                dzCourseScheduling.setStudyDate(arr[i]);
                String week = dateToWeek(arr[i]);
                //设置状态
                dzCourseScheduling.setState(type);
                //设置星期
                dzCourseScheduling.setWeek(week);
                dzCourseSchedulingService.insertDzCourseScheduling(dzCourseScheduling);
                //获取排课ID
                Long ScheduleId = dzCourseScheduling.getId();
                //获取班级ID
                String classId = dzCourseScheduling.getClassId();
                //查询班级详情
                Schoolclass schoolclass = schoolclassService.selectSchoolclassById(Long.parseLong(classId));
                //获取学生列表
                String classStudent = schoolclass.getClassStudent();
                if (classStudent != null && classStudent.length() > 0) {
                    String[] arrclassStudent = classStudent.split(",");
                    dzCourseScheduling.setClassStudent(""+arrclassStudent.length);
                    dzCourseSchedulingService.updateDzCourseScheduling(dzCourseScheduling);

                    for (int z = 0; z < arrclassStudent.length; z++) {
                        //获取学生信息
                        DzStudent dzStudent = dzStudentService.selectDzStudentById(Long.parseLong(arrclassStudent[z]));
                        //获取学生ID
                        Long studentId = dzStudent.getId();
                        //获取学生姓名
                        String userName = dzStudent.getUserName();
                        //获取联系方式
                        String phonenumber = dzStudent.getPhonenumber();
                        String RemainingClassHours = dzStudent.getRemainingClassHours();
                        //新建一个记录
                        ClassRecords classRecords = new ClassRecords();
                        //设置学生ID
                        classRecords.setStudentId(studentId.toString());

                        //设置学生名称
                        classRecords.setStudentName(userName);
                        //设置总时长
                        classRecords.setRemainingclasshours(RemainingClassHours);
                        //设置联系方式
                        classRecords.setLinkPhone(phonenumber);
                        //设置课程名字
                        classRecords.setCourseName(dzCourseScheduling.getClassCourse());
                        //设置课程ID
                        classRecords.setCourseId(dzCourseScheduling.getClassCourseId());
                        //设置班级名称
                        classRecords.setClassName(dzCourseScheduling.getClassName());
                        //设置班级ID
                        classRecords.setClassId(dzCourseScheduling.getClassId());
                        //设置机构ID
                        classRecords.setDeptId(dzCourseScheduling.getDeptId());
                        //设置日期
                        classRecords.setDate(arr[i]);
                        //设置时间
                        classRecords.setTime(dzCourseScheduling.getClassStart() + "-" + dzCourseScheduling.getClassFinish());
                       //设置老师
                        classRecords.setTeacher(dzCourseScheduling.getClassTeacher());
                        //设置排课ID
                        classRecords.setScheduleId(ScheduleId);
                        //设置排课状态
//                        classRecords.setAttendanceState("");
                        //设置消课数量
                        classRecords.setCourseCancellations(dzCourseScheduling.getClassHours());
                        classRecordsService.insertClassRecords(classRecords);

                    }
                }


            }
            return toAjax(true);
        } catch (Exception e) {
            return toAjax(false);
        }


    }

    /**
     * 日期转星期
     *
     * @param datetime "2017-01-01"
     * @return
     */
    public static String dateToWeek(String datetime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance(); // 获得一个日历
        Date datet = null;
        try {
            datet = f.parse(datetime);
            cal.setTime(datet);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    /**
     * 修改课程表
     */
    @PreAuthorize("@ss.hasPermi('scheduling:scheduling:edit')")
    @Log(title = "课程表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DzCourseScheduling dzCourseScheduling) throws ParseException {
        String ids = dzCourseScheduling.getData1();
        if (ids != null) {
            if (dzCourseScheduling.getState() != null) {
                String[] splitid = ids.split(",");
                System.out.println(splitid);
                List<DzCourseScheduling> list = dzCourseSchedulingService.getDzCourseSchedulingByIds(splitid);
                for (int i = 0; i < list.size(); i++) {
                    //获得当前日期
                    String remark6 = list.get(i).getStudyDate();
                    //更新延后天数
                    Calendar calendar = Calendar.getInstance();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    calendar.setTime(simpleDateFormat.parse(remark6));
                    //        //加2天
                    calendar.add(Calendar.DATE, Integer.parseInt(dzCourseScheduling.getState()));
                    String format = simpleDateFormat.format(calendar.getTime());
                    //获得更新日期
                    System.out.println(format);
                    list.get(i).setStudyDate(format);
                    int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

                    // 将数字转换成相应的星期名称
                    String weekdayName = "";
                    switch (dayOfWeek) {
                        case Calendar.SUNDAY:
                            weekdayName = "星期天";
                            break;
                        case Calendar.MONDAY:
                            weekdayName = "星期一";
                            break;
                        case Calendar.TUESDAY:
                            weekdayName = "星期二";
                            break;
                        case Calendar.WEDNESDAY:
                            weekdayName = "星期三";
                            break;
                        case Calendar.THURSDAY:
                            weekdayName = "星期四";
                            break;
                        case Calendar.FRIDAY:
                            weekdayName = "星期五";
                            break;
                        case Calendar.SATURDAY:
                            weekdayName = "星期六";
                            break;
                    }
                    list.get(i).setWeek(weekdayName);
                    dzCourseSchedulingService.updateDzCourseScheduling(list.get(i));
                }



            } else {

                String[] arr = ids.split(",");
                for (int i = 0; i < arr.length; i++) {
                    dzCourseScheduling.setId(Long.parseLong(arr[i]));
                    dzCourseSchedulingService.updateDzCourseScheduling(dzCourseScheduling);
                }
            }
            return toAjax(true);
        }else {


            UPDATESettlement();

            return toAjax(dzCourseSchedulingService.updateDzCourseScheduling(dzCourseScheduling));
        }



    }

    /**
     * 删除课程表
     */
    @PreAuthorize("@ss.hasPermi('scheduling:scheduling:remove')")
    @Log(title = "课程表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(dzCourseSchedulingService.deleteDzCourseSchedulingByIds(ids));
    }

    @Autowired
    private IWithholdingFeesService withholdingFeesService;
    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderDeductService orderDeductService;


    //及时结算 结算一次
    public  void  UPDATESettlement() throws ParseException {
        List<WithholdingFees> WithholdingFeeslist = withholdingFeesService.selectWithholdingFeesList(null);
        for (int i=0; i<WithholdingFeeslist.size(); i++) {
            WithholdingFees withholdingFees = WithholdingFeeslist.get(i);
            String studentId =withholdingFees .getStudentId();
            int intNumber =withholdingFees .getNumber();
//            int intNumber = Integer.parseInt(Number);
            Order order=new Order();
            order.setStudentId(studentId);
            order.setOrderRemark10("0");

            List<Order> list = orderService.selectOrderList(order);
            //如果有此用户的订单
            if (list.size()>0) {
                Order order1 = list.get(0);
                //获取单价
                String unitPrice = order1.getUnitPrice();
                //int单价
                float intunitPrice = Float.parseFloat(unitPrice);
                //获取已消课数量
                String consumed = order1.getConsumed();
                //获取已消课数量
                int intconsumed = Integer.parseInt(consumed);
                //累计已消课数量
                int nowintconsumed=intconsumed+intNumber;
                //设置已消课数量
                order1.setConsumed(""+nowintconsumed);
                //累计已消课金额
                float  consumedmoney= nowintconsumed*intunitPrice;
                //设置已消费金额
                order1.setMoneyDetermined(""+consumedmoney);
                //获取剩余课程数量
                String residue = order1.getResidue();
                //获取剩余课程数量int
                int intresidue = Integer.parseInt(residue);
                //对订单进行扣费，计算剩余扣费金额
                int nownumer=  intresidue-intNumber;

                //添加订单扣费记录
                OrderDeduct orderDeduct=new OrderDeduct();
                orderDeduct.setOrderId(""+order1.getOrderId());
                orderDeduct.setStudentId(""+order1.getStudentId());
                orderDeduct.setNumber(intNumber);
                orderDeduct.setCourseId(withholdingFees.getCourseId());

                orderDeduct.setScheduleId(""+withholdingFees.getScheduleId());
                orderDeduct.setDeptId(withholdingFees.getDeptId());
                //获取课程信息
                DzCourseScheduling dzCourseScheduling = dzCourseSchedulingService.selectDzCourseSchedulingById(Long.parseLong(withholdingFees.getScheduleId()));
                if (dzCourseScheduling!=null) {
                    orderDeduct.setClassTime(dzCourseScheduling.getStudyDate()+" "+dzCourseScheduling.getClassStart()+"-"+dzCourseScheduling.getClassFinish());

                }


                orderDeductService.insertOrderDeduct(orderDeduct);

                if (nownumer>0) {
                    //够扣费,设置剩余课时
                    order1.setResidue(""+nownumer);


                    //计算未确认收入
                    float unmoney=  nownumer*intunitPrice;
                    //设置未确认收入
                    order1.setMoneyUnconfirmed(""+unmoney);

                    order1.setState("进行中");
                    orderService.updateOrder(order1);
                    //删除待扣费记录
                    withholdingFeesService.deleteWithholdingFeesById(withholdingFees.getId());



                } else {



                    //设置剩余课时
                    order1.setResidue("0");
                    //设置未扣费收入
                    order1.setMoneyUnconfirmed("0" );
                    order1.setState("已完结");
                    order1.setOrderRemark10("1");
                    //不够扣费
                    int positivenownumer = Math.abs(nownumer);
                    withholdingFees.setNumber( positivenownumer);
                    orderService.updateOrder(order1);
                    //更新待扣费
                    withholdingFeesService.updateWithholdingFees(withholdingFees);

                }

                Order orderquery=new Order();
                orderquery.setStudentId(studentId);
                orderquery.setOrderRemark10("0");

                List<Order> Orderlist = orderService.selectOrderList(orderquery);
                int value=0;
                for (int w=0; w<Orderlist.size(); w++) {
                    String residue1 = Orderlist.get(w).getResidue();
                    int intresidue1 = Integer.parseInt(residue1);
                    //剩余课数量
                    value=value+intresidue1;


                }
                //更新用户信息
                DzStudent dzStudent = dzStudentService.selectDzStudentById(Long.parseLong(order.getStudentId()));
                dzStudent.setRemainingClassHours(""+value);
                dzStudentService.updateDzStudent(dzStudent);


                ClassRecords classRecords=new ClassRecords();
                classRecords.setStudentId(order.getStudentId());
                List<ClassRecords> classRecords1 = classRecordsService.selectClassRecordsList(classRecords);
                for (int z=0; z<classRecords1.size(); z++) {

                    classRecords1.get(z).setRemainingclasshours(""+value);


                    //更新记录中的剩余课时数
                    classRecordsService.updateClassRecords(classRecords1.get(z));



                }





            } else {

                //无订单，不更新

            }



        }


    }

}
